// Copyright 2020 The Tilt Brush Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

Shader "Custom/FlipbookWithAlpha" {
    Properties{
        _Color("Color", Color) = (1,1,1,1)
        _MainTex("Base (RGB) TransGloss (A)", 2D) = "white" {}
    _TexWidth("Texture Width", Float) = 1
    _CellAmount("Cell Amount", Float) = 4
    _Cutoff("Alpha Cutoff", Float) = 0.5
    _Multiplier("Flipbook Speed", Float) = 2
    }
        SubShader{
        Tags {"Queue"="AlphaTest" "IgnoreProjector"="True" "RenderType"="TransparentCutout"}
        LOD 100

        CGPROGRAM
        #pragma target 3.0
        #pragma surface surf Lambert nofog

        float _CellAmount;
        float _TexWidth;
        float _Cutoff;
    float _Multiplier;

    struct Input {
        float2 uv_MainTex;
        float4 color : Color;
    };

        sampler2D _MainTex;
        fixed4 _Color;

    void surf(Input IN, inout SurfaceOutput o) {

        fixed2 scrollUV = IN.uv_MainTex;

        // Calculate UV scroll amount based on texture size and number of frames.
        // Default _TexWidth should be 1, augment for weirder uses.
        float cellPixelWidth = _TexWidth / _CellAmount;
        float cellUVpercentage = cellPixelWidth / _TexWidth;

        // Animate flipbook motion.
    // Multiplier added for tuning
        float anim = fmod(_Time.y * _Multiplier, _CellAmount);
        anim = ceil(anim);
        scrollUV.x += anim;
        scrollUV.x *= cellUVpercentage;

        // Discard transparent pixels.
        if (tex2D(_MainTex, scrollUV).a < _Cutoff)
            discard;

        half4 c = tex2D(_MainTex, scrollUV);
        o.Emission = c.rgb * _Color.rgb;
    }

    ENDCG
    }
        FallBack "Diffuse"
}
